package com.fingard.dsp.bank.directbank.tfb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TFB01Transaction extends TFB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            TFB01Header header = new TFB01Header();
            header.bsnCode = "QueryCurDtl";
            header.serialNo = p_req7516.reqHeader.transSeqID;
            header.msgType = "account";
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            String pageSize = getBankConfig().getValueAsString("pageSize");
            pageSize = StringHelper.isNullOrEmpty(pageSize)?"10":pageSize;
            while (tmpIntDateFrom <= tmpIntDateTo && StringHelper.isNullOrEmpty(tmpRespCode)) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                int tmpPageNumber = 0;//页码数，默认查询第一页
                int tmpNowReadedCount = 0;//是否有下一页
                int tmpReadNum = 0;///读取总条数
                boolean tmpQryNext = true;
                while (tmpNowReadedCount == 0 && tmpQryNext) {//分页查询
                    XmlTextWriter xmlWriter = new XmlTextWriter();//发送银行报文的XML对象
                    //写入通用的头部节点
                    writeCommonHeader(xmlWriter, header);
                    xmlWriter.writeStartElement("map");
                    xmlWriter.writeElementString("bgamnt", "");
                    xmlWriter.writeElementString("edamnt", "");
                    xmlWriter.writeElementString("accNo", p_req7516.actNum);
                    xmlWriter.writeElementString("begnno", String.valueOf(tmpPageNumber));
                    xmlWriter.writeElementString("rcrdnm", pageSize);
                    xmlWriter.writeElementString("prov", "");
                    xmlWriter.writeElementString("city", "");
                    xmlWriter.writeElementString("accName", "");
                    xmlWriter.writeElementString("openBranchName", "");
                    xmlWriter.writeElementString("toacct", "");
                    xmlWriter.writeElementString("toacna", "");
                    xmlWriter.writeElementString("cur", this.getBankConfig().getMapValueByKey("currencyMapping",p_req7516.actCur));
                    xmlWriter.writeElementString("startDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));
                    xmlWriter.writeElementString("endDate", Format.Date10Format.format(tmpClndrStepTo.getTime()));

                    xmlWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                    if (tmpStrRet[0].length() == 0) {
                            StringBuilder tmpSbMsg = new StringBuilder();
                            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                            if (tmpBkReader != null) {
                                String respondCode = tmpBkReader.getFirstText("/body/head/retCode");
                                String respondInfo = tmpBkReader.getFirstText("/body/head/retMsg");
                                if(respondCode.equals("000000")) {
                                        while (tmpBkReader.read("/body/loopData/map")) {
                                            tmpNowReadedCount++;
                                            tmpReadNum ++ ;
                                            RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                            tmpRetDetail.actNum = p_req7516.actNum;
                                            tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("payeeAccNo");
                                            tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("payeeAccName");
                                            tmpRetDetail.recAccBank = tmpBkReader.readedXElement.getSingleText("payeeOpenBranchName>");
                                            String tmpTranDate = tmpBkReader.readedXElement.getSingleText("transTime");
                                            if(tmpTranDate.length()>10 ){
                                                tmpTranDate = tmpTranDate.substring(0,10);
                                            }
                                            tmpRetDetail.tranDate = tmpTranDate;
                                            String tmpTranTime = timestampToDate(tmpBkReader.readedXElement.getSingleText("transTime"));//交易时间戳
                                            if(StringHelper.isNullOrEmpty(tmpTranTime)){
                                                tmpTranTime =tmpTranDate + " 00:00:00";
                                            }
                                            tmpRetDetail.tranTime = tmpTranTime;
                                            tmpRetDetail.valueDate = tmpTranDate;//起息日没有返回就用交易日
                                            tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance");

                                            String tmpTranAmt = tmpBkReader.readedXElement.getSingleText("amt");
                                            String tmpDCFlag = tmpBkReader.readedXElement.getSingleText("cdsign");
                                            tmpDCFlag = "0".equals(tmpDCFlag) ? "1" : "2";
                                            tmpRetDetail.tranAmt = tmpTranAmt;
                                            tmpRetDetail.cdFlag = tmpDCFlag;
                                            String tmpPurpose = tmpBkReader.readedXElement.getSingleText("postScript");
                                            String[] tmpArr = tmpPurpose.split("-");
                                            if (tmpArr.length >= 2) {
                                                tmpRetDetail.usage = tmpArr[0];
                                                tmpRetDetail.abstr = tmpArr[1];
                                            } else {
                                                tmpRetDetail.usage = tmpPurpose;
                                            }
                                            tmpRetDetail.cur = p_req7516.actCur;
                                            retAts.writeRetDetail(tmpRetDetail);
                                        }
                                        if(tmpReadNum==0){
                                            tmpRespCode = "0";
                                            tmpRespInfo = "未找到明细记录";
                                        }
                                        if(tmpNowReadedCount<Integer.valueOf(pageSize)){
                                            tmpQryNext = false;
                                            tmpNowReadedCount = 0;
                                        }
                                }else{
                                    tmpRespCode = "-1";
                                    tmpRespInfo = respondCode + ":" + respondInfo;
                                    break;
                                }

                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpSbMsg.toString();
                                break;
                            }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpStrRet[1];
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
